# 统计服务模块
import pandas as pd

class StatisticsService:
    def __init__(self, db_session):
        self.db_session = db_session
        
    def get_trading_statistics(self, user_id, period='week'):
        """
        获取交易统计数据
        :param user_id: 用户ID
        :param period: 周期 ('day', 'week', 'month', 'year')
        :return: 统计数据
        """
        # 获取用户交易历史
        trades = self._get_user_trades(user_id, period)
        
        if not trades:
            return {
                'period': period,
                'total_trades': 0,
                'win_rate': 0,
                'avg_profit_loss': 0,
                'total_profit_loss': 0
            }
        
        # 计算统计指标
        total_trades = len(trades)
        win_trades = [t for t in trades if t['profit_loss'] > 0]
        win_rate = len(win_trades) / total_trades if total_trades > 0 else 0
        avg_profit_loss = sum(t['profit_loss'] for t in trades) / total_trades if total_trades > 0 else 0
        total_profit_loss = sum(t['profit_loss'] for t in trades)
        
        return {
            'period': period,
            'total_trades': total_trades,
            'win_rate': win_rate,
            'avg_profit_loss': avg_profit_loss,
            'total_profit_loss': total_profit_loss
        }
        
    def get_portfolio_stats(self, user_id):
        """
        获取投资组合统计数据
        :param user_id: 用户ID
        :return: 投资组合统计数据
        """
        # 获取用户投资组合
        portfolio = self._get_user_portfolio(user_id)
        
        # 计算统计指标
        total_value = portfolio['cash'] + portfolio['portfolio_value']
        stock_allocation = {k: v['value']/total_value for k, v in portfolio['stocks'].items()}
        
        return {
            'total_value': total_value,
            'cash': portfolio['cash'],
            'portfolio_value': portfolio['portfolio_value'],
            'stock_allocation': stock_allocation,
            'top_stock': max(portfolio['stocks'].items(), key=lambda x: x[1]['value'], default=None)
        }
        
    def _get_user_trades(self, user_id, period):
        """
        获取用户交易历史
        :param user_id: 用户ID
        :param period: 周期
        :return: 交易历史
        """
        # 从数据库获取用户交易历史
        # 这里是模拟数据
        return [
            {'id': 1, 'stock_code': 'AAPL', 'trade_type': 'buy', 'price': 150, 'quantity': 10, 'profit_loss': 200},
            {'id': 2, 'stock_code': 'MSFT', 'trade_type': 'buy', 'price': 300, 'quantity': 5, 'profit_loss': -50},
            {'id': 3, 'stock_code': 'GOOG', 'trade_type': 'buy', 'price': 120, 'quantity': 20, 'profit_loss': 300}
        ]
        
    def _get_user_portfolio(self, user_id):
        """
        获取用户投资组合
        :param user_id: 用户ID
        :return: 投资组合
        """
        # 从数据库获取用户投资组合
        # 这里是模拟数据
        return {
            'cash': 100000,
            'portfolio_value': 150000,
            'stocks': {
                'AAPL': {'quantity': 10, 'price': 170, 'value': 1700},
                'MSFT': {'quantity': 5, 'price': 290, 'value': 1450},
                'GOOG': {'quantity': 20, 'price': 135, 'value': 2700}
            }
        }